<!--
系统状态监控组件 - 重新构建版本
简洁的卡片式设计，显示核心系统指标
-->
<script setup lang="ts">
import type { SystemHealthInfo } from '#/api/monitor/system';

import { onMounted, onUnmounted, ref } from 'vue';

import { AnalysisChartCard } from '@vben/common-ui';

import { getSystemStatus } from '#/api/monitor/system';

// 组件状态
const systemInfo = ref<null | SystemHealthInfo>(null);
const loading = ref(false);
const error = ref<null | string>(null);

// 定时器
let refreshTimer: NodeJS.Timeout | null = null;

/**
 * 获取系统状态信息
 */
async function fetchSystemStatus() {
  try {
    loading.value = true;
    error.value = null;

    const status = await getSystemStatus();
    systemInfo.value = status;
  } catch (error_) {
    console.error('获取系统状态失败:', error_);
    error.value = '获取系统状态失败';
  } finally {
    loading.value = false;
  }
}

/**
 * 设置定时刷新
 */
function setupRefresh() {
  refreshTimer = setInterval(() => {
    fetchSystemStatus();
  }, 30_000);
}

/**
 * 清理定时器
 */
function clearRefresh() {
  if (refreshTimer) {
    clearInterval(refreshTimer);
    refreshTimer = null;
  }
}

/**
 * 格式化数字
 */
function formatNumber(num: number): string {
  if (num >= 1000) {
    return `${(num / 1000).toFixed(1)}k`;
  }
  return num.toString();
}

/**
 * 获取状态颜色
 */
function getStatusColor(
  value: number,
  type: 'health' | 'usage' = 'usage',
): string {
  if (type === 'health') {
    if (value >= 80) return 'text-green-600';
    if (value >= 60) return 'text-yellow-600';
    return 'text-red-600';
  } else {
    if (value >= 80) return 'text-red-600';
    if (value >= 60) return 'text-yellow-600';
    return 'text-green-600';
  }
}

/**
 * 获取进度条颜色
 */
function getProgressColor(
  value: number,
  type: 'health' | 'usage' = 'usage',
): string {
  if (type === 'health') {
    if (value >= 80) return 'bg-green-500';
    if (value >= 60) return 'bg-yellow-500';
    return 'bg-red-500';
  } else {
    if (value >= 80) return 'bg-red-500';
    if (value >= 60) return 'bg-yellow-500';
    return 'bg-green-500';
  }
}

// 生命周期钩子
onMounted(() => {
  fetchSystemStatus();
  setupRefresh();
});

onUnmounted(() => {
  clearRefresh();
});
</script>

<template>
  <AnalysisChartCard title="系统状态">
    <div class="h-80">
      <!-- 加载状态 -->
      <div
        v-if="loading"
        class="flex h-full items-center justify-center text-gray-500"
      >
        <div class="flex items-center space-x-2">
          <div
            class="h-4 w-4 animate-spin rounded-full border-2 border-blue-500 border-t-transparent"
          ></div>
          <span>正在获取系统状态...</span>
        </div>
      </div>

      <!-- 错误状态 -->
      <div
        v-else-if="error"
        class="flex h-full items-center justify-center text-red-500"
      >
        <div class="text-center">
          <div class="mb-2">⚠️</div>
          <div>{{ error }}</div>
          <button
            class="mt-2 rounded bg-red-100 px-3 py-1 text-sm transition-colors hover:bg-red-200"
            @click="fetchSystemStatus"
          >
            重试
          </button>
        </div>
      </div>

      <!-- 系统状态内容 -->
      <div v-else-if="systemInfo" class="h-full p-1">
        <!-- 第一行：核心指标 -->
        <div class="mb-3 grid grid-cols-4 gap-3">
          <!-- 系统健康度 -->
          <div
            class="rounded-lg border border-green-200 bg-gradient-to-r from-green-50 to-green-100 p-3"
          >
            <div class="mb-1 flex items-center justify-between">
              <span class="text-sm font-medium text-green-600">系统健康度</span>
              <span
                :class="getStatusColor(systemInfo.healthScore, 'health')"
                class="text-lg font-bold"
              >
                {{ systemInfo.healthScore }}%
              </span>
            </div>
            <div class="h-2 rounded-full bg-gray-200">
              <div
                :class="getProgressColor(systemInfo.healthScore, 'health')"
                class="h-2 rounded-full transition-all duration-500"
                :style="{ width: `${systemInfo.healthScore}%` }"
              ></div>
            </div>
          </div>

          <!-- CPU使用率 -->
          <div
            class="rounded-lg border border-blue-200 bg-gradient-to-r from-blue-50 to-blue-100 p-3"
          >
            <div class="mb-1 flex items-center justify-between">
              <span class="text-sm font-medium text-blue-600">CPU使用率</span>
              <span
                :class="getStatusColor(systemInfo.cpuUsage)"
                class="text-lg font-bold"
              >
                {{ systemInfo.cpuUsage }}%
              </span>
            </div>
            <div class="h-2 rounded-full bg-gray-200">
              <div
                :class="getProgressColor(systemInfo.cpuUsage)"
                class="h-2 rounded-full transition-all duration-500"
                :style="{ width: `${systemInfo.cpuUsage}%` }"
              ></div>
            </div>
          </div>

          <!-- 内存使用率 -->
          <div
            class="rounded-lg border border-purple-200 bg-gradient-to-r from-purple-50 to-purple-100 p-3"
          >
            <div class="mb-1 flex items-center justify-between">
              <span class="text-sm font-medium text-purple-600"
                >内存使用率</span
              >
              <span
                :class="getStatusColor(systemInfo.memoryUsage)"
                class="text-lg font-bold"
              >
                {{ systemInfo.memoryUsage }}%
              </span>
            </div>
            <div class="h-2 rounded-full bg-gray-200">
              <div
                :class="getProgressColor(systemInfo.memoryUsage)"
                class="h-2 rounded-full transition-all duration-500"
                :style="{ width: `${systemInfo.memoryUsage}%` }"
              ></div>
            </div>
          </div>

          <!-- 磁盘使用率 -->
          <div
            class="rounded-lg border border-orange-200 bg-gradient-to-r from-orange-50 to-orange-100 p-3"
          >
            <div class="mb-1 flex items-center justify-between">
              <span class="text-sm font-medium text-orange-600"
                >磁盘使用率</span
              >
              <span
                :class="getStatusColor(systemInfo.diskUsage)"
                class="text-lg font-bold"
              >
                {{ systemInfo.diskUsage }}%
              </span>
            </div>
            <div class="h-2 rounded-full bg-gray-200">
              <div
                :class="getProgressColor(systemInfo.diskUsage)"
                class="h-2 rounded-full transition-all duration-500"
                :style="{ width: `${systemInfo.diskUsage}%` }"
              ></div>
            </div>
          </div>
        </div>

        <!-- 第二行：网络和服务状态 -->
        <div class="mb-3 grid grid-cols-4 gap-3">
          <!-- 网络流量 -->
          <div class="rounded-lg border border-cyan-200 bg-cyan-50 p-3">
            <div class="mb-1 text-sm font-medium text-cyan-600">网络流量</div>
            <div class="text-xs text-gray-700">
              <div>↑ {{ systemInfo.networkUpload }}MB/s</div>
              <div>↓ {{ systemInfo.networkDownload }}MB/s</div>
            </div>
          </div>

          <!-- 数据库连接 -->
          <div class="rounded-lg border border-indigo-200 bg-indigo-50 p-3">
            <div class="mb-1 text-sm font-medium text-indigo-600">数据库</div>
            <div class="text-xs text-gray-700">
              <div>连接: {{ systemInfo.dbConnections }}</div>
              <div>错误率: {{ systemInfo.errorRate }}%</div>
            </div>
          </div>

          <!-- 缓存状态 -->
          <div class="rounded-lg border border-teal-200 bg-teal-50 p-3">
            <div class="mb-1 text-sm font-medium text-teal-600">缓存命中率</div>
            <div class="text-gray-700">
              <span class="text-lg font-bold"
                >{{ systemInfo.cacheHitRate }}%</span
              >
            </div>
          </div>

          <!-- 在线用户 -->
          <div class="rounded-lg border border-pink-200 bg-pink-50 p-3">
            <div class="mb-1 text-sm font-medium text-pink-600">在线用户</div>
            <div class="text-gray-700">
              <span class="text-lg font-bold">{{
                systemInfo.onlineUsers
              }}</span>
            </div>
          </div>
        </div>

        <!-- 第三行：系统信息 -->
        <div class="grid grid-cols-2 gap-3">
          <!-- 系统运行时间 -->
          <div class="rounded-lg border bg-gray-50 p-3">
            <div class="mb-2 text-sm font-medium text-gray-600">系统信息</div>
            <div class="space-y-1 text-xs text-gray-700">
              <div>运行时间: {{ systemInfo.uptime }}小时</div>
              <div>系统温度: {{ systemInfo.temperature }}°C</div>
              <div>
                API请求: {{ formatNumber(systemInfo.apiRequests) }}/分钟
              </div>
            </div>
          </div>

          <!-- 存储详情 -->
          <div class="rounded-lg border bg-gray-50 p-3">
            <div class="mb-2 text-sm font-medium text-gray-600">存储详情</div>
            <div class="space-y-1 text-xs text-gray-700">
              <div>
                内存: {{ systemInfo.usedMemory }}GB /
                {{ systemInfo.totalMemory }}GB
              </div>
              <div>
                磁盘: {{ systemInfo.usedDisk }}GB / {{ systemInfo.totalDisk }}GB
              </div>
              <div class="text-gray-500">
                更新: {{ new Date(systemInfo.updateTime).toLocaleTimeString() }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </AnalysisChartCard>
</template>

<style scoped>
.animate-spin {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
